package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ArticleHomeMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleHomeService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.mess.ArticleEsMess;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-12 15:27
 */
@Service
public class ArticleHomeServiceImpl implements ArticleHomeService {

    @Autowired
    private ArticleHomeMapper articleHomeMapper;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;
    @Autowired
    private CacheService cacheService;

    /**
     *
     * @param dto
     * @param loadType
     * @param isIndex 代表是否是首页数据，是首页从redis取，反之从数据库中获取
     * @return
     */
    @Override
    public List<ApArticle> load(ArticleHomeDto dto, Short loadType,boolean isIndex) {

        if(isIndex){
            //从redis中获取
            String articles = cacheService.get(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC + dto.getTag());
            if(StringUtils.isNotBlank(articles)){
                return JSON.parseArray(articles, ApArticle.class);
            }
        }

        //1.校验参数
        if(dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() > 50){
            dto.setSize(10);
        }

        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //2.查询
        Page<ApArticle> page = new Page<>();
        page.setCurrent(1);
        page.setSize(dto.getSize());
        //修改count查询不执行
        page.setSearchCount(false);

        IPage<ApArticle> result = articleHomeMapper.load(page,dto.getSize(),dto.getTag()
                ,dto.getMaxBehotTime(),dto.getMinBehotTime(),loadType);

        return result.getRecords();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(ArticleDto dto) {

        //判断是否存在文章id
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);

        if(dto.getId() != null){
            //修改
            apArticleMapper.updateById(apArticle);
            //更新文章内容
            apArticleContentMapper.update(null, Wrappers
                    .<ApArticleContent>lambdaUpdate()
                    .eq(ApArticleContent::getArticleId,dto.getId())
                    .set(ApArticleContent::getContent,dto.getContent())
            );

        }else{
            //新增

            //主表
            apArticle.setCreatedTime(new Date());
            apArticleMapper.insert(apArticle);

            //编写配置表
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(apArticleContent);

        }
        //生成静态页面
        articleFreemarkerService.createStaticUrl(apArticle,dto.getContent());


        return apArticle.getId();
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = simpleDateFormat.parse("2020-09-08 10:20:12");
        System.out.println(parse.getTime());
    }
}
